home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / lib / python2.6 / threading.py < prev    next >
Text File  |  2009-11-02  |  31KB  |  961 lines

  1. """Thread module emulating a subset of Java's threading model."""
  2.  
  3. import sys as _sys
  4.  
  5. try:
  6.     import thread
  7. except ImportError:
  8.     del _sys.modules[__name__]
  9.     raise
  10.  
  11. import warnings
  12.  
  13. from functools import wraps
  14. from time import time as _time, sleep as _sleep
  15. from traceback import format_exc as _format_exc
  16. from collections import deque
  17.  
  18. # Note regarding PEP 8 compliant aliases
  19. #  This threading model was originally inspired by Java, and inherited
  20. # the convention of camelCase function and method names from that
  21. # language. While those names are not in any imminent danger of being
  22. # deprecated, starting with Python 2.6, the module now provides a
  23. # PEP 8 compliant alias for any such method name.
  24. # Using the new PEP 8 compliant names also facilitates substitution
  25. # with the multiprocessing module, which doesn't provide the old
  26. # Java inspired names.
  27.  
  28.  
  29. # Rename some stuff so "from threading import *" is safe
  30. __all__ = ['activeCount', 'active_count', 'Condition', 'currentThread',
  31.            'current_thread', 'enumerate', 'Event',
  32.            'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
  33.            'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
  34.  
  35. _start_new_thread = thread.start_new_thread
  36. _allocate_lock = thread.allocate_lock
  37. _get_ident = thread.get_ident
  38. ThreadError = thread.error
  39. del thread
  40.  
  41.  
  42. # sys.exc_clear is used to work around the fact that except blocks
  43. # don't fully clear the exception until 3.0.
  44. warnings.filterwarnings('ignore', category=DeprecationWarning,
  45.                         module='threading', message='sys.exc_clear')
  46.  
  47. # Debug support (adapted from ihooks.py).
  48. # All the major classes here derive from _Verbose.  We force that to
  49. # be a new-style class so that all the major classes here are new-style.
  50. # This helps debugging (type(instance) is more revealing for instances
  51. # of new-style classes).
  52.  
  53. _VERBOSE = False
  54.  
  55. if __debug__:
  56.  
  57.     class _Verbose(object):
  58.  
  59.         def __init__(self, verbose=None):
  60.             if verbose is None:
  61.                 verbose = _VERBOSE
  62.             self.__verbose = verbose
  63.  
  64.         def _note(self, format, *args):
  65.             if self.__verbose:
  66.                 format = format % args
  67.                 format = "%s: %s\n" % (
  68.                     current_thread().name, format)
  69.                 _sys.stderr.write(format)
  70.  
  71. else:
  72.     # Disable this when using "python -O"
  73.     class _Verbose(object):
  74.         def __init__(self, verbose=None):
  75.             pass
  76.         def _note(self, *args):
  77.             pass
  78.  
  79. # Support for profile and trace hooks
  80.  
  81. _profile_hook = None
  82. _trace_hook = None
  83.  
  84. def setprofile(func):
  85.     global _profile_hook
  86.     _profile_hook = func
  87.  
  88. def settrace(func):
  89.     global _trace_hook
  90.     _trace_hook = func
  91.  
  92. # Synchronization classes
  93.  
  94. Lock = _allocate_lock
  95.  
  96. def RLock(*args, **kwargs):
  97.     return _RLock(*args, **kwargs)
  98.  
  99. class _RLock(_Verbose):
  100.  
  101.     def __init__(self, verbose=None):
  102.         _Verbose.__init__(self, verbose)
  103.         self.__block = _allocate_lock()
  104.         self.__owner = None
  105.         self.__count = 0
  106.  
  107.     def __repr__(self):
  108.         owner = self.__owner
  109.         return "<%s(%s, %d)>" % (
  110.                 self.__class__.__name__,
  111.                 owner and owner.name,
  112.                 self.__count)
  113.  
  114.     def acquire(self, blocking=1):
  115.         me = current_thread()
  116.         if self.__owner is me:
  117.             self.__count = self.__count + 1
  118.             if __debug__:
  119.                 self._note("%s.acquire(%s): recursive success", self, blocking)
  120.             return 1
  121.         rc = self.__block.acquire(blocking)
  122.         if rc:
  123.             self.__owner = me
  124.             self.__count = 1
  125.             if __debug__:
  126.                 self._note("%s.acquire(%s): initial success", self, blocking)
  127.         else:
  128.             if __debug__:
  129.                 self._note("%s.acquire(%s): failure", self, blocking)
  130.         return rc
  131.  
  132.     __enter__ = acquire
  133.  
  134.     def release(self):
  135.         if self.__owner is not current_thread():
  136.             raise RuntimeError("cannot release un-aquired lock")
  137.         self.__count = count = self.__count - 1
  138.         if not count:
  139.             self.__owner = None
  140.             self.__block.release()
  141.             if __debug__:
  142.                 self._note("%s.release(): final release", self)
  143.         else:
  144.             if __debug__:
  145.                 self._note("%s.release(): non-final release", self)
  146.  
  147.     def __exit__(self, t, v, tb):
  148.         self.release()
  149.  
  150.     # Internal methods used by condition variables
  151.  
  152.     def _acquire_restore(self, count_owner):
  153.         count, owner = count_owner
  154.         self.__block.acquire()
  155.         self.__count = count
  156.         self.__owner = owner
  157.         if __debug__:
  158.             self._note("%s._acquire_restore()", self)
  159.  
  160.     def _release_save(self):
  161.         if __debug__:
  162.             self._note("%s._release_save()", self)
  163.         count = self.__count
  164.         self.__count = 0
  165.         owner = self.__owner
  166.         self.__owner = None
  167.         self.__block.release()
  168.         return (count, owner)
  169.  
  170.     def _is_owned(self):
  171.         return self.__owner is current_thread()
  172.  
  173.  
  174. def Condition(*args, **kwargs):
  175.     return _Condition(*args, **kwargs)
  176.  
  177. class _Condition(_Verbose):
  178.  
  179.     def __init__(self, lock=None, verbose=None):
  180.         _Verbose.__init__(self, verbose)
  181.         if lock is None:
  182.             lock = RLock()
  183.         self.__lock = lock
  184.         # Export the lock's acquire() and release() methods
  185.         self.acquire = lock.acquire
  186.         self.release = lock.release
  187.         # If the lock defines _release_save() and/or _acquire_restore(),
  188.         # these override the default implementations (which just call
  189.         # release() and acquire() on the lock).  Ditto for _is_owned().
  190.         try:
  191.             self._release_save = lock._release_save
  192.         except AttributeError:
  193.             pass
  194.         try:
  195.             self._acquire_restore = lock._acquire_restore
  196.         except AttributeError:
  197.             pass
  198.         try:
  199.             self._is_owned = lock._is_owned
  200.         except AttributeError:
  201.             pass
  202.         self.__waiters = []
  203.  
  204.     def __enter__(self):
  205.         return self.__lock.__enter__()
  206.  
  207.     def __exit__(self, *args):
  208.         return self.__lock.__exit__(*args)
  209.  
  210.     def __repr__(self):
  211.         return "<Condition(%s, %d)>" % (self.__lock, len(self.__waiters))
  212.  
  213.     def _release_save(self):
  214.         self.__lock.release()           # No state to save
  215.  
  216.     def _acquire_restore(self, x):
  217.         self.__lock.acquire()           # Ignore saved state
  218.  
  219.     def _is_owned(self):
  220.         # Return True if lock is owned by current_thread.
  221.         # This method is called only if __lock doesn't have _is_owned().
  222.         if self.__lock.acquire(0):
  223.             self.__lock.release()
  224.             return False
  225.         else:
  226.             return True
  227.  
  228.     def wait(self, timeout=None):
  229.         if not self._is_owned():
  230.             raise RuntimeError("cannot wait on un-aquired lock")
  231.         waiter = _allocate_lock()
  232.         waiter.acquire()
  233.         self.__waiters.append(waiter)
  234.         saved_state = self._release_save()
  235.         try:    # restore state no matter what (e.g., KeyboardInterrupt)
  236.             if timeout is None:
  237.                 waiter.acquire()
  238.                 if __debug__:
  239.                     self._note("%s.wait(): got it", self)
  240.             else:
  241.                 # Balancing act:  We can't afford a pure busy loop, so we
  242.                 # have to sleep; but if we sleep the whole timeout time,
  243.                 # we'll be unresponsive.  The scheme here sleeps very
  244.                 # little at first, longer as time goes on, but never longer
  245.                 # than 20 times per second (or the timeout time remaining).
  246.                 endtime = _time() + timeout
  247.                 delay = 0.0005 # 500 us -> initial delay of 1 ms
  248.                 while True:
  249.                     gotit = waiter.acquire(0)
  250.                     if gotit:
  251.                         break
  252.                     remaining = endtime - _time()
  253.                     if remaining <= 0:
  254.                         break
  255.                     delay = min(delay * 2, remaining, .05)
  256.                     _sleep(delay)
  257.                 if not gotit:
  258.                     if __debug__:
  259.                         self._note("%s.wait(%s): timed out", self, timeout)
  260.                     try:
  261.                         self.__waiters.remove(waiter)
  262.                     except ValueError:
  263.                         pass
  264.                 else:
  265.                     if __debug__:
  266.                         self._note("%s.wait(%s): got it", self, timeout)
  267.         finally:
  268.             self._acquire_restore(saved_state)
  269.  
  270.     def notify(self, n=1):
  271.         if not self._is_owned():
  272.             raise RuntimeError("cannot notify on un-aquired lock")
  273.         __waiters = self.__waiters
  274.         waiters = __waiters[:n]
  275.         if not waiters:
  276.             if __debug__:
  277.                 self._note("%s.notify(): no waiters", self)
  278.             return
  279.         self._note("%s.notify(): notifying %d waiter%s", self, n,
  280.                    n!=1 and "s" or "")
  281.         for waiter in waiters:
  282.             waiter.release()
  283.             try:
  284.                 __waiters.remove(waiter)
  285.             except ValueError:
  286.                 pass
  287.  
  288.     def notifyAll(self):
  289.         self.notify(len(self.__waiters))
  290.  
  291.     notify_all = notifyAll
  292.  
  293.  
  294. def Semaphore(*args, **kwargs):
  295.     return _Semaphore(*args, **kwargs)
  296.  
  297. class _Semaphore(_Verbose):
  298.  
  299.     # After Tim Peters' semaphore class, but not quite the same (no maximum)
  300.  
  301.     def __init__(self, value=1, verbose=None):
  302.         if value < 0:
  303.             raise ValueError("semaphore initial value must be >= 0")
  304.         _Verbose.__init__(self, verbose)
  305.         self.__cond = Condition(Lock())
  306.         self.__value = value
  307.  
  308.     def acquire(self, blocking=1):
  309.         rc = False
  310.         self.__cond.acquire()
  311.         while self.__value == 0:
  312.             if not blocking:
  313.                 break
  314.             if __debug__:
  315.                 self._note("%s.acquire(%s): blocked waiting, value=%s",
  316.                            self, blocking, self.__value)
  317.             self.__cond.wait()
  318.         else:
  319.             self.__value = self.__value - 1
  320.             if __debug__:
  321.                 self._note("%s.acquire: success, value=%s",
  322.                            self, self.__value)
  323.             rc = True
  324.         self.__cond.release()
  325.         return rc
  326.  
  327.     __enter__ = acquire
  328.  
  329.     def release(self):
  330.         self.__cond.acquire()
  331.         self.__value = self.__value + 1
  332.         if __debug__:
  333.             self._note("%s.release: success, value=%s",
  334.                        self, self.__value)
  335.         self.__cond.notify()
  336.         self.__cond.release()
  337.  
  338.     def __exit__(self, t, v, tb):
  339.         self.release()
  340.  
  341.  
  342. def BoundedSemaphore(*args, **kwargs):
  343.     return _BoundedSemaphore(*args, **kwargs)
  344.  
  345. class _BoundedSemaphore(_Semaphore):
  346.     """Semaphore that checks that # releases is <= # acquires"""
  347.     def __init__(self, value=1, verbose=None):
  348.         _Semaphore.__init__(self, value, verbose)
  349.         self._initial_value = value
  350.  
  351.     def release(self):
  352.         if self._Semaphore__value >= self._initial_value:
  353.             raise ValueError, "Semaphore released too many times"
  354.         return _Semaphore.release(self)
  355.  
  356.  
  357. def Event(*args, **kwargs):
  358.     return _Event(*args, **kwargs)
  359.  
  360. class _Event(_Verbose):
  361.  
  362.     # After Tim Peters' event class (without is_posted())
  363.  
  364.     def __init__(self, verbose=None):
  365.         _Verbose.__init__(self, verbose)
  366.         self.__cond = Condition(Lock())
  367.         self.__flag = False
  368.  
  369.     def isSet(self):
  370.         return self.__flag
  371.  
  372.     is_set = isSet
  373.  
  374.     def set(self):
  375.         self.__cond.acquire()
  376.         try:
  377.             self.__flag = True
  378.             self.__cond.notify_all()
  379.         finally:
  380.             self.__cond.release()
  381.  
  382.     def clear(self):
  383.         self.__cond.acquire()
  384.         try:
  385.             self.__flag = False
  386.         finally:
  387.             self.__cond.release()
  388.  
  389.     def wait(self, timeout=None):
  390.         self.__cond.acquire()
  391.         try:
  392.             if not self.__flag:
  393.                 self.__cond.wait(timeout)
  394.         finally:
  395.             self.__cond.release()
  396.  
  397. # Helper to generate new thread names
  398. _counter = 0
  399. def _newname(template="Thread-%d"):
  400.     global _counter
  401.     _counter = _counter + 1
  402.     return template % _counter
  403.  
  404. # Active thread administration
  405. _active_limbo_lock = _allocate_lock()
  406. _active = {}    # maps thread id to Thread object
  407. _limbo = {}
  408.  
  409.  
  410. # Main class for threads
  411.  
  412. class Thread(_Verbose):
  413.  
  414.     __initialized = False
  415.     # Need to store a reference to sys.exc_info for printing
  416.     # out exceptions when a thread tries to use a global var. during interp.
  417.     # shutdown and thus raises an exception about trying to perform some
  418.     # operation on/with a NoneType
  419.     __exc_info = _sys.exc_info
  420.     # Keep sys.exc_clear too to clear the exception just before
  421.     # allowing .join() to return.
  422.     __exc_clear = _sys.exc_clear
  423.  
  424.     def __init__(self, group=None, target=None, name=None,
  425.                  args=(), kwargs=None, verbose=None):
  426.         assert group is None, "group argument must be None for now"
  427.         _Verbose.__init__(self, verbose)
  428.         if kwargs is None:
  429.             kwargs = {}
  430.         self.__target = target
  431.         self.__name = str(name or _newname())
  432.         self.__args = args
  433.         self.__kwargs = kwargs
  434.         self.__daemonic = self._set_daemon()
  435.         self.__ident = None
  436.         self.__started = Event()
  437.         self.__stopped = False
  438.         self.__block = Condition(Lock())
  439.         self.__initialized = True
  440.         # sys.stderr is not stored in the class like
  441.         # sys.exc_info since it can be changed between instances
  442.         self.__stderr = _sys.stderr
  443.  
  444.     def _set_daemon(self):
  445.         # Overridden in _MainThread and _DummyThread
  446.         return current_thread().daemon
  447.  
  448.     def __repr__(self):
  449.         assert self.__initialized, "Thread.__init__() was not called"
  450.         status = "initial"
  451.         if self.__started.is_set():
  452.             status = "started"
  453.         if self.__stopped:
  454.             status = "stopped"
  455.         if self.__daemonic:
  456.             status += " daemon"
  457.         if self.__ident is not None:
  458.             status += " %s" % self.__ident
  459.         return "<%s(%s, %s)>" % (self.__class__.__name__, self.__name, status)
  460.  
  461.     def start(self):
  462.         if not self.__initialized:
  463.             raise RuntimeError("thread.__init__() not called")
  464.         if self.__started.is_set():
  465.             raise RuntimeError("thread already started")
  466.         if __debug__:
  467.             self._note("%s.start(): starting thread", self)
  468.         _active_limbo_lock.acquire()
  469.         _limbo[self] = self
  470.         _active_limbo_lock.release()
  471.         _start_new_thread(self.__bootstrap, ())
  472.         self.__started.wait()
  473.  
  474.     def run(self):
  475.         try:
  476.             if self.__target:
  477.                 self.__target(*self.__args, **self.__kwargs)
  478.         finally:
  479.             # Avoid a refcycle if the thread is running a function with
  480.             # an argument that has a member that points to the thread.
  481.             del self.__target, self.__args, self.__kwargs
  482.  
  483.     def __bootstrap(self):
  484.         # Wrapper around the real bootstrap code that ignores
  485.         # exceptions during interpreter cleanup.  Those typically
  486.         # happen when a daemon thread wakes up at an unfortunate
  487.         # moment, finds the world around it destroyed, and raises some
  488.         # random exception *** while trying to report the exception in
  489.         # __bootstrap_inner() below ***.  Those random exceptions
  490.         # don't help anybody, and they confuse users, so we suppress
  491.         # them.  We suppress them only when it appears that the world
  492.         # indeed has already been destroyed, so that exceptions in
  493.         # __bootstrap_inner() during normal business hours are properly
  494.         # reported.  Also, we only suppress them for daemonic threads;
  495.         # if a non-daemonic encounters this, something else is wrong.
  496.         try:
  497.             self.__bootstrap_inner()
  498.         except:
  499.             if self.__daemonic and _sys is None:
  500.                 return
  501.             raise
  502.  
  503.     def _set_ident(self):
  504.         self.__ident = _get_ident()
  505.  
  506.     def __bootstrap_inner(self):
  507.         try:
  508.             self._set_ident()
  509.             self.__started.set()
  510.             _active_limbo_lock.acquire()
  511.             _active[self.__ident] = self
  512.             del _limbo[self]
  513.             _active_limbo_lock.release()
  514.             if __debug__:
  515.                 self._note("%s.__bootstrap(): thread started", self)
  516.  
  517.             if _trace_hook:
  518.                 self._note("%s.__bootstrap(): registering trace hook", self)
  519.                 _sys.settrace(_trace_hook)
  520.             if _profile_hook:
  521.                 self._note("%s.__bootstrap(): registering profile hook", self)
  522.                 _sys.setprofile(_profile_hook)
  523.  
  524.             try:
  525.                 self.run()
  526.             except SystemExit:
  527.                 if __debug__:
  528.                     self._note("%s.__bootstrap(): raised SystemExit", self)
  529.             except:
  530.                 if __debug__:
  531.                     self._note("%s.__bootstrap(): unhandled exception", self)
  532.                 # If sys.stderr is no more (most likely from interpreter
  533.                 # shutdown) use self.__stderr.  Otherwise still use sys (as in
  534.                 # _sys) in case sys.stderr was redefined since the creation of
  535.                 # self.
  536.                 if _sys:
  537.                     _sys.stderr.write("Exception in thread %s:\n%s\n" %
  538.                                       (self.name, _format_exc()))
  539.                 else:
  540.                     # Do the best job possible w/o a huge amt. of code to
  541.                     # approximate a traceback (code ideas from
  542.                     # Lib/traceback.py)
  543.                     exc_type, exc_value, exc_tb = self.__exc_info()
  544.                     try:
  545.                         print>>self.__stderr, (
  546.                             "Exception in thread " + self.name +
  547.                             " (most likely raised during interpreter shutdown):")
  548.                         print>>self.__stderr, (
  549.                             "Traceback (most recent call last):")
  550.                         while exc_tb:
  551.                             print>>self.__stderr, (
  552.                                 '  File "%s", line %s, in %s' %
  553.                                 (exc_tb.tb_frame.f_code.co_filename,
  554.                                     exc_tb.tb_lineno,
  555.                                     exc_tb.tb_frame.f_code.co_name))
  556.                             exc_tb = exc_tb.tb_next
  557.                         print>>self.__stderr, ("%s: %s" % (exc_type, exc_value))
  558.                     # Make sure that exc_tb gets deleted since it is a memory
  559.                     # hog; deleting everything else is just for thoroughness
  560.                     finally:
  561.                         del exc_type, exc_value, exc_tb
  562.             else:
  563.                 if __debug__:
  564.                     self._note("%s.__bootstrap(): normal return", self)
  565.             finally:
  566.                 # Prevent a race in
  567.                 # test_threading.test_no_refcycle_through_target when
  568.                 # the exception keeps the target alive past when we
  569.                 # assert that it's dead.
  570.                 self.__exc_clear()
  571.         finally:
  572.             with _active_limbo_lock:
  573.                 self.__stop()
  574.                 try:
  575.                     # We don't call self.__delete() because it also
  576.                     # grabs _active_limbo_lock.
  577.                     del _active[_get_ident()]
  578.                 except:
  579.                     pass
  580.  
  581.     def __stop(self):
  582.         self.__block.acquire()
  583.         self.__stopped = True
  584.         self.__block.notify_all()
  585.         self.__block.release()
  586.  
  587.     def __delete(self):
  588.         "Remove current thread from the dict of currently running threads."
  589.  
  590.         # Notes about running with dummy_thread:
  591.         #
  592.         # Must take care to not raise an exception if dummy_thread is being
  593.         # used (and thus this module is being used as an instance of
  594.         # dummy_threading).  dummy_thread.get_ident() always returns -1 since
  595.         # there is only one thread if dummy_thread is being used.  Thus
  596.         # len(_active) is always <= 1 here, and any Thread instance created
  597.         # overwrites the (if any) thread currently registered in _active.
  598.         #
  599.         # An instance of _MainThread is always created by 'threading'.  This
  600.         # gets overwritten the instant an instance of Thread is created; both
  601.         # threads return -1 from dummy_thread.get_ident() and thus have the
  602.         # same key in the dict.  So when the _MainThread instance created by
  603.         # 'threading' tries to clean itself up when atexit calls this method
  604.         # it gets a KeyError if another Thread instance was created.
  605.         #
  606.         # This all means that KeyError from trying to delete something from
  607.         # _active if dummy_threading is being used is a red herring.  But
  608.         # since it isn't if dummy_threading is *not* being used then don't
  609.         # hide the exception.
  610.  
  611.         try:
  612.             with _active_limbo_lock:
  613.                 del _active[_get_ident()]
  614.                 # There must not be any python code between the previous line
  615.                 # and after the lock is released.  Otherwise a tracing function
  616.                 # could try to acquire the lock again in the same thread, (in
  617.                 # current_thread()), and would block.
  618.         except KeyError:
  619.             if 'dummy_threading' not in _sys.modules:
  620.                 raise
  621.  
  622.     def join(self, timeout=None):
  623.         if not self.__initialized:
  624.             raise RuntimeError("Thread.__init__() not called")
  625.         if not self.__started.is_set():
  626.             raise RuntimeError("cannot join thread before it is started")
  627.         if self is current_thread():
  628.             raise RuntimeError("cannot join current thread")
  629.  
  630.         if __debug__:
  631.             if not self.__stopped:
  632.                 self._note("%s.join(): waiting until thread stops", self)
  633.         self.__block.acquire()
  634.         try:
  635.             if timeout is None:
  636.                 while not self.__stopped:
  637.                     self.__block.wait()
  638.                 if __debug__:
  639.                     self._note("%s.join(): thread stopped", self)
  640.             else:
  641.                 deadline = _time() + timeout
  642.                 while not self.__stopped:
  643.                     delay = deadline - _time()
  644.                     if delay <= 0:
  645.                         if __debug__:
  646.                             self._note("%s.join(): timed out", self)
  647.                         break
  648.                     self.__block.wait(delay)
  649.                 else:
  650.                     if __debug__:
  651.                         self._note("%s.join(): thread stopped", self)
  652.         finally:
  653.             self.__block.release()
  654.  
  655.     @property
  656.     def name(self):
  657.         assert self.__initialized, "Thread.__init__() not called"
  658.         return self.__name
  659.  
  660.     @name.setter
  661.     def name(self, name):
  662.         assert self.__initialized, "Thread.__init__() not called"
  663.         self.__name = str(name)
  664.  
  665.     @property
  666.     def ident(self):
  667.         assert self.__initialized, "Thread.__init__() not called"
  668.         return self.__ident
  669.  
  670.     def isAlive(self):
  671.         assert self.__initialized, "Thread.__init__() not called"
  672.         return self.__started.is_set() and not self.__stopped
  673.  
  674.     is_alive = isAlive
  675.  
  676.     @property
  677.     def daemon(self):
  678.         assert self.__initialized, "Thread.__init__() not called"
  679.         return self.__daemonic
  680.  
  681.     @daemon.setter
  682.     def daemon(self, daemonic):
  683.         if not self.__initialized:
  684.             raise RuntimeError("Thread.__init__() not called")
  685.         if self.__started.is_set():
  686.             raise RuntimeError("cannot set daemon status of active thread");
  687.         self.__daemonic = daemonic
  688.  
  689.     def isDaemon(self):
  690.         return self.daemon
  691.  
  692.     def setDaemon(self, daemonic):
  693.         self.daemon = daemonic
  694.  
  695.     def getName(self):
  696.         return self.name
  697.  
  698.     def setName(self, name):
  699.         self.name = name
  700.  
  701. # The timer class was contributed by Itamar Shtull-Trauring
  702.  
  703. def Timer(*args, **kwargs):
  704.     return _Timer(*args, **kwargs)
  705.  
  706. class _Timer(Thread):
  707.     """Call a function after a specified number of seconds:
  708.  
  709.     t = Timer(30.0, f, args=[], kwargs={})
  710.     t.start()
  711.     t.cancel() # stop the timer's action if it's still waiting
  712.     """
  713.  
  714.     def __init__(self, interval, function, args=[], kwargs={}):
  715.         Thread.__init__(self)
  716.         self.interval = interval
  717.         self.function = function
  718.         self.args = args
  719.         self.kwargs = kwargs
  720.         self.finished = Event()
  721.  
  722.     def cancel(self):
  723.         """Stop the timer if it hasn't finished yet"""
  724.         self.finished.set()
  725.  
  726.     def run(self):
  727.         self.finished.wait(self.interval)
  728.         if not self.finished.is_set():
  729.             self.function(*self.args, **self.kwargs)
  730.         self.finished.set()
  731.  
  732. # Special thread class to represent the main thread
  733. # This is garbage collected through an exit handler
  734.  
  735. class _MainThread(Thread):
  736.  
  737.     def __init__(self):
  738.         Thread.__init__(self, name="MainThread")
  739.         self._Thread__started.set()
  740.         self._set_ident()
  741.         _active_limbo_lock.acquire()
  742.         _active[_get_ident()] = self
  743.         _active_limbo_lock.release()
  744.  
  745.     def _set_daemon(self):
  746.         return False
  747.  
  748.     def _exitfunc(self):
  749.         self._Thread__stop()
  750.         t = _pickSomeNonDaemonThread()
  751.         if t:
  752.             if __debug__:
  753.                 self._note("%s: waiting for other threads", self)
  754.         while t:
  755.             t.join()
  756.             t = _pickSomeNonDaemonThread()
  757.         if __debug__:
  758.             self._note("%s: exiting", self)
  759.         self._Thread__delete()
  760.  
  761. def _pickSomeNonDaemonThread():
  762.     for t in enumerate():
  763.         if not t.daemon and t.is_alive():
  764.             return t
  765.     return None
  766.  
  767.  
  768. # Dummy thread class to represent threads not started here.
  769. # These aren't garbage collected when they die, nor can they be waited for.
  770. # If they invoke anything in threading.py that calls current_thread(), they
  771. # leave an entry in the _active dict forever after.
  772. # Their purpose is to return *something* from current_thread().
  773. # They are marked as daemon threads so we won't wait for them
  774. # when we exit (conform previous semantics).
  775.  
  776. class _DummyThread(Thread):
  777.  
  778.     def __init__(self):
  779.         Thread.__init__(self, name=_newname("Dummy-%d"))
  780.  
  781.         # Thread.__block consumes an OS-level locking primitive, which
  782.         # can never be used by a _DummyThread.  Since a _DummyThread
  783.         # instance is immortal, that's bad, so release this resource.
  784.         del self._Thread__block
  785.  
  786.         self._Thread__started.set()
  787.         self._set_ident()
  788.         _active_limbo_lock.acquire()
  789.         _active[_get_ident()] = self
  790.         _active_limbo_lock.release()
  791.  
  792.     def _set_daemon(self):
  793.         return True
  794.  
  795.     def join(self, timeout=None):
  796.         assert False, "cannot join a dummy thread"
  797.  
  798.  
  799. # Global API functions
  800.  
  801. def currentThread():
  802.     try:
  803.         return _active[_get_ident()]
  804.     except KeyError:
  805.         ##print "current_thread(): no current thread for", _get_ident()
  806.         return _DummyThread()
  807.  
  808. current_thread = currentThread
  809.  
  810. def activeCount():
  811.     _active_limbo_lock.acquire()
  812.     count = len(_active) + len(_limbo)
  813.     _active_limbo_lock.release()
  814.     return count
  815.  
  816. active_count = activeCount
  817.  
  818. def enumerate():
  819.     _active_limbo_lock.acquire()
  820.     active = _active.values() + _limbo.values()
  821.     _active_limbo_lock.release()
  822.     return active
  823.  
  824. from thread import stack_size
  825.  
  826. # Create the main thread object,
  827. # and make it available for the interpreter
  828. # (Py_Main) as threading._shutdown.
  829.  
  830. _shutdown = _MainThread()._exitfunc
  831.  
  832. # get thread-local implementation, either from the thread
  833. # module, or from the python fallback
  834.  
  835. try:
  836.     from thread import _local as local
  837. except ImportError:
  838.     from _threading_local import local
  839.  
  840.  
  841. def _after_fork():
  842.     # This function is called by Python/ceval.c:PyEval_ReInitThreads which
  843.     # is called from PyOS_AfterFork.  Here we cleanup threading module state
  844.     # that should not exist after a fork.
  845.  
  846.     # Reset _active_limbo_lock, in case we forked while the lock was held
  847.     # by another (non-forked) thread.  http://bugs.python.org/issue874900
  848.     global _active_limbo_lock
  849.     _active_limbo_lock = _allocate_lock()
  850.  
  851.     # fork() only copied the current thread; clear references to others.
  852.     new_active = {}
  853.     current = current_thread()
  854.     with _active_limbo_lock:
  855.         for thread in _active.itervalues():
  856.             if thread is current:
  857.                 # There is only one active thread. We reset the ident to
  858.                 # its new value since it can have changed.
  859.                 ident = _get_ident()
  860.                 thread._Thread__ident = ident
  861.                 new_active[ident] = thread
  862.             else:
  863.                 # All the others are already stopped.
  864.                 # We don't call _Thread__stop() because it tries to acquire
  865.                 # thread._Thread__block which could also have been held while
  866.                 # we forked.
  867.                 thread._Thread__stopped = True
  868.  
  869.         _limbo.clear()
  870.         _active.clear()
  871.         _active.update(new_active)
  872.         assert len(_active) == 1
  873.  
  874.  
  875. # Self-test code
  876.  
  877. def _test():
  878.  
  879.     class BoundedQueue(_Verbose):
  880.  
  881.         def __init__(self, limit):
  882.             _Verbose.__init__(self)
  883.             self.mon = RLock()
  884.             self.rc = Condition(self.mon)
  885.             self.wc = Condition(self.mon)
  886.             self.limit = limit
  887.             self.queue = deque()
  888.  
  889.         def put(self, item):
  890.             self.mon.acquire()
  891.             while len(self.queue) >= self.limit:
  892.                 self._note("put(%s): queue full", item)
  893.                 self.wc.wait()
  894.             self.queue.append(item)
  895.             self._note("put(%s): appended, length now %d",
  896.                        item, len(self.queue))
  897.             self.rc.notify()
  898.             self.mon.release()
  899.  
  900.         def get(self):
  901.             self.mon.acquire()
  902.             while not self.queue:
  903.                 self._note("get(): queue empty")
  904.                 self.rc.wait()
  905.             item = self.queue.popleft()
  906.             self._note("get(): got %s, %d left", item, len(self.queue))
  907.             self.wc.notify()
  908.             self.mon.release()
  909.             return item
  910.  
  911.     class ProducerThread(Thread):
  912.  
  913.         def __init__(self, queue, quota):
  914.             Thread.__init__(self, name="Producer")
  915.             self.queue = queue
  916.             self.quota = quota
  917.  
  918.         def run(self):
  919.             from random import random
  920.             counter = 0
  921.             while counter < self.quota:
  922.                 counter = counter + 1
  923.                 self.queue.put("%s.%d" % (self.name, counter))
  924.                 _sleep(random() * 0.00001)
  925.  
  926.  
  927.     class ConsumerThread(Thread):
  928.  
  929.         def __init__(self, queue, count):
  930.             Thread.__init__(self, name="Consumer")
  931.             self.queue = queue
  932.             self.count = count
  933.  
  934.         def run(self):
  935.             while self.count > 0:
  936.                 item = self.queue.get()
  937.                 print item
  938.                 self.count = self.count - 1
  939.  
  940.     NP = 3
  941.     QL = 4
  942.     NI = 5
  943.  
  944.     Q = BoundedQueue(QL)
  945.     P = []
  946.     for i in range(NP):
  947.         t = ProducerThread(Q, NI)
  948.         t.name = ("Producer-%d" % (i+1))
  949.         P.append(t)
  950.     C = ConsumerThread(Q, NI*NP)
  951.     for t in P:
  952.         t.start()
  953.         _sleep(0.000001)
  954.     C.start()
  955.     for t in P:
  956.         t.join()
  957.     C.join()
  958.  
  959. if __name__ == '__main__':
  960.     _test()
  961.